package cn.taofuxn.sale.service.impl;

import cn.taofuxn.sale.bean.TbProducer;
import cn.taofuxn.sale.controller.data.AddProducerRequest;
import cn.taofuxn.sale.controller.data.ModifyProducerRequest;
import cn.taofuxn.sale.dao.ProducerDao;
import cn.taofuxn.sale.service.ProducerService;
import cn.taofuxn.sale.service.data.base.BasePageResponse;
import cn.taofuxn.sale.service.data.base.BaseResult;
import cn.taofuxn.sale.service.data.base.ResultCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * ProjectName : GeekSaleSystem
 * PackageName : cn.taofuxn.sale.service.impl
 * Created by Wong
 * Date: 2018/4/12
 * Time: 17:31
 */
@Service
public class ProducerServiceImpl implements ProducerService {
	
	@Autowired
	private ProducerDao m_ProducerDao;
	
	@SuppressWarnings("Duplicates")
	@Override
	public BaseResult getProducer(final int vPage, final int vPageSize) {
		PageRequest tPageRequest = new PageRequest(vPage, vPageSize);
		Page tGoodsPage = m_ProducerDao.findAll(tPageRequest);
		BasePageResponse tResponse = new BasePageResponse();
		tResponse.setInfos(tGoodsPage.getContent());
		tResponse.setTotal((int) tGoodsPage.getTotalElements());
		tResponse.setTotalPage(tGoodsPage.getTotalPages());
		return BaseResult.success(tResponse);
	}
	
	@Override
	public BaseResult addProducer(final AddProducerRequest vRequest) {
		List<TbProducer> tProducers = m_ProducerDao.findByName(vRequest.getName());
		if(!CollectionUtils.isEmpty(tProducers)){
			return BaseResult.generate(ResultCodeType.PRODUCER_NAME_DUPLICATE);
		}
		
		TbProducer  tTbProducer = new TbProducer();
		tTbProducer.setAddress(vRequest.getAddress());
		tTbProducer.setNote(vRequest.getNote());
		tTbProducer.setName(vRequest.getName());
		tTbProducer.setLevel(vRequest.getLevel());
		tTbProducer.setPhone(vRequest.getPhone());
		return BaseResult.success(m_ProducerDao.save(tTbProducer));
	}
	
	@Override
	public BaseResult modifyProducer(final ModifyProducerRequest vRequest) {
		TbProducer tTbProducer = m_ProducerDao.findOne(vRequest.getId());
		if(null == tTbProducer){
			return BaseResult.generate(ResultCodeType.NOT_FOUND_PRODUCER);
		}
		
		tTbProducer.setAddress(vRequest.getAddress());
		tTbProducer.setNote(vRequest.getNote());
		tTbProducer.setName(vRequest.getName());
		tTbProducer.setLevel(vRequest.getLevel());
		tTbProducer.setPhone(vRequest.getPhone());
		
		return BaseResult.success(m_ProducerDao.save(tTbProducer));
	}
	
	
	@Override
	public BaseResult deleteProducer(final String vOrderId) {
		m_ProducerDao.delete(vOrderId);
		return BaseResult.success();
	}
}
